package org.example.traing.WebSocket;

import org.apache.ibatis.type.CharacterTypeHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
import org.springframework.web.socket.server.HandshakeInterceptor;

import java.util.Map;



@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {

    @Autowired
   /* private final*/ ChatHandler chatHandler;

    /*public WebSocketConfig(ChatHandler chatHandler) {
        this.chatHandler = chatHandler;
    }*/

    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        registry.addHandler(chatHandler, "/chat/{roomId}")
                .addInterceptors(new HandshakeInterceptor() {
                    @Override
                    public boolean beforeHandshake(
                            org.springframework.http.server.ServerHttpRequest request,
                            org.springframework.http.server.ServerHttpResponse response,
                            WebSocketHandler wsHandler,
                            Map<String, Object> attributes) throws Exception {
                        // 从 URL 中提取 roomId 并存储到 session 的属性中
                        if (request instanceof org.springframework.http.server.ServletServerHttpRequest) {
                            String path = ((org.springframework.http.server.ServletServerHttpRequest) request)
                                    .getServletRequest().getRequestURI();
                            String roomId = path.substring(path.lastIndexOf('/') + 1);
                            attributes.put("roomId", roomId);
                        }
                        return true;
                    }

                    @Override
                    public void afterHandshake(
                            org.springframework.http.server.ServerHttpRequest request,
                            org.springframework.http.server.ServerHttpResponse response,
                            WebSocketHandler wsHandler, Exception ex) {
                        // 无需实现
                    }
                }).setAllowedOrigins("*");
    }
}

